import Mn from 'backbone.marionette';
import SelectWidget from '../../../widgets/SelectWidget.js';
import TextAreaWidget from '../../../widgets/TextAreaWidget.js';
import {getDefaultItem} from '../../../tools.js';
import FormBehavior from '../../../base/behaviors/FormBehavior.js';
import Radio from 'backbone.radio';
import Validation from 'backbone-validation';

var template = require("./templates/PaymentConditionBlockView.mustache");

const PaymentConditionBlockView = Mn.View.extend({
    behaviors: [FormBehavior],
    tagName: 'div',
    className: 'separate_block border_left_block',
    template: template,
    regions: {
        errors: ".errors",
        predefined_conditions: '.predefined-conditions',
        conditions: '.conditions',
    },
    modelEvents: {
        'change:payment_conditions': 'render',
        'validated:invalid': 'showErrors',
        'validated:valid': 'hideErrors',
    },
    childViewEvents: {
        'finish': 'onFinish',
    },
    initialize: function(){
        this.config = Radio.channel('config')
        this.payment_conditions_options = this.config.request(
            'get:options', 'payment_conditions'
        );
        this.lookupDefault();

        var channel = Radio.channel('facade');
        this.listenTo(channel, 'bind:validation', this.bindValidation);
        this.listenTo(channel, 'unbind:validation', this.unbindValidation);
    },
    bindValidation(){
        Validation.bind(this);
    },
    unbindValidation(){
        Validation.unbind(this);
    },
    showErrors(model, errors){
        this.$el.addClass('error');
    },
    hideErrors(model){
        this.$el.removeClass('error');
    },
    onFinish(field_name, value){
        if (field_name == 'predefined_conditions'){
            var condition_object = this.getCondition(value);

            this.model.set('predefined_conditions', value);
            if (!_.isUndefined(condition_object)){
                this.triggerMethod('data:persist', 'payment_conditions', condition_object.label);
            }
        } else {
            this.triggerMethod('data:persist', 'payment_conditions', value);
        }
    },
    getCondition(id){
        return _.find(
            this.payment_conditions_options,
            function(item){ return item.id == id;}
        );
    },
    lookupDefault(){
        /*
         * Setup the default payment condition if none is set
         */
        var option = getDefaultItem(this.payment_conditions_options);
        if (!_.isUndefined(option)){
            var payment_conditions = this.model.get('payment_conditions');
            if (_.isUndefined(payment_conditions) || payment_conditions === null || payment_conditions.trim() == ''){
                this.model.set('payment_conditions', option.label);
                this.model.save({'payment_conditions': option.label}, {patch: true});
            }
        }
    },
    onRender: function(){
        // #FIXME : Je ne suis pas sûr que ce champ existe dans le modèle,
        // je le laisse dans le doute
        var val = this.model.get('predefined_conditions');
        val = parseInt(val, 10);
        this.showChildView(
            'predefined_conditions',
            new SelectWidget(
                {
                    options: this.payment_conditions_options,
                    title: "Conditions de paiement prédéfinies",
                    field_name: 'predefined_conditions',
                    id_key: 'id',
                    value: val,
                    placeholder: '',
                }
            )
        );
        this.showChildView(
            'conditions',
            new TextAreaWidget(
                {
                    label: "Conditions de paiement applicables à ce document",
                    value: this.model.get('payment_conditions'),
                    field_name: 'payment_conditions',
                    description: 'Vous pouvez personnaliser les conditions prédéfinies pour les appliquer à votre document.',
                    required: true
                }
            )
        );
    },
    templateContext(){
        let collapsed = false;
        const default_condition = _.findWhere(this.payment_conditions_options, {default: true});
        if (! _.isUndefined(default_condition)){
            collapsed = true;
        }
        return {collapsed: collapsed};


    }
});
export default PaymentConditionBlockView;
